package com.qianli.cashmama.trade.application.offer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.StringUtils;
import com.qianli.cashmama.trade.client.offer.QuoteQueryService;
import com.qianli.cashmama.trade.client.offer.response.OfferResponse;
import com.qianli.cashmama.trade.client.vo.OfferVO;
import com.qianli.cashmama.trade.common.enums.TradeBorrowDurationEnum;
import com.qianli.cashmama.trade.common.exceptions.TradeException;
import com.qianli.cashmama.trade.common.utils.CalculatorUtils;
import com.qianli.cashmama.trade.common.utils.TradeConfigUtil;
import com.qianli.cashmama.trade.integration.product.ProductIntegrationService;
import com.qianli.cashmama.trade.integration.product.dto.ProductDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2017/7/31
 * Time: 上午11:10
 */
@Service("quoteQueryService")
public class QuoteQueryServiceImpl implements QuoteQueryService {
    private static final Logger LOGGER = LoggerFactory.getLogger(QuoteQueryServiceImpl.class);

    @Autowired
    private ProductIntegrationService productIntegrationService;

    @Autowired
    private TradeConfigUtil configUtil;


    @Override
    public Response<OfferResponse> quoteDetail(String productCode) {
        Response<OfferResponse> response = new Response<>();
        ProductDto productDto = productIntegrationService.getProductInfoByCode(productCode);
        if (productDto == null) {
            return response.ok().putData(null);
        }

        try {
            return response.ok().putData(productDtoToOfferResponse(productDto));
        } catch (TradeException e) {
            LOGGER.error("== 获取报价失败 ==,productCode:{},e", productCode, e);
            return response.error(e.getErrorEnum());
        }
    }


    @Override
    public Response<Map<String, OfferResponse>> quoteDetailMap(List<String> productCodeList) {
        LOGGER.info("== 报价map ==,params:{}", JSON.toJSONString(productCodeList));

        String downProductCategories = configUtil.disabled_product_code();
        Response<Map<String, OfferResponse>> response = new Response<>();

        if (CollectionUtils.isEmpty(productCodeList)) {
            return response.ok().putData(null);
        }

        Map<String, ProductDto> productDtoMap = productIntegrationService.getProductDtoMap(productCodeList);
        Map<String, OfferResponse> res = new HashMap<>();

        for (String productCode : productDtoMap.keySet()) {
            if (StringUtils.isNotEmpty(downProductCategories) && downProductCategories.contains(productCode)) {
                LOGGER.info("== 报价map,有类目暂时不提供报价==,productCode:{}", productCode);
                continue;
            }

            OfferResponse offerResponse = productDtoToOfferResponse(productDtoMap.get(productCode));
            if (offerResponse != null) {
                res.put(productCode, offerResponse);
            }
        }

        return response.ok().putData(res);
    }


    private OfferResponse productDtoToOfferResponse(ProductDto productDto) {
        try {
            BigDecimal borrowTotalCapital = productDto.getBorrowTotalCapital();
            BigDecimal totalReceivedCapital = productDto.getReceivedTotalCapital();
            BigDecimal totalServiceFee = productDto.getTotalServiceFee();

            LOGGER.info("productDto is {}", JSONObject.toJSONString(productDto));
            int totalPeriods = productDto.getTotalPeriod();
            BigDecimal borrowCapital = CalculatorUtils.calculateBorrowCapital(borrowTotalCapital, totalPeriods);
            BigDecimal receivedCapital = CalculatorUtils.calculateReceivedCapital(totalReceivedCapital, totalPeriods);
            BigDecimal serviceFee = CalculatorUtils.calculateServiceFee(totalServiceFee, totalPeriods);
            BigDecimal interestFee = CalculatorUtils.calculateInterestFee(borrowCapital, productDto.getBorrowRatio(), productDto.getPeriodLength());

            List<OfferVO> offerVOList = new ArrayList<>();
            for (int i = 1; i <= totalPeriods; i++) {
                OfferVO offerVO = new OfferVO()
                        .setProductCategory(productDto.getProductCategory())
                        .setProductCode(productDto.getProductCode())
                        .setBorrowCapital(productDto.getBorrowTotalCapital().toString())
                        .setCurrentPeriod(i);
                //最后一期
                if (i == totalPeriods) {
                    offerVO.setBorrowCapital(CalculatorUtils.calculateLastBorrowCapital(borrowTotalCapital, totalPeriods).toString())
                            .setReceivedCapital(CalculatorUtils.calculateLastReceivedCapital(totalReceivedCapital, totalPeriods).toString())
                            .setInterestFee(interestFee.toString())
                            .setServiceFee(CalculatorUtils.calculateLastServiceFee(totalServiceFee, totalPeriods).toEngineeringString());
                } else {
                    offerVO.setBorrowCapital(borrowCapital.toString())
                            .setReceivedCapital(receivedCapital.toString())
                            .setServiceFee(serviceFee.toString())
                            .setInterestFee(interestFee.toString());
                }

                offerVOList.add(offerVO);
            }

            OfferResponse offerResponse = new OfferResponse()
                    .setProductCategory(productDto.getProductCategory())
                    .setProductCode(productDto.getProductCode())
                    .setBorrowTotalCapital(borrowTotalCapital.toString())
                    .setReceivedTotalCapital(totalReceivedCapital.toString())
                    .setTotalServiceFee(totalServiceFee.toString())
                    .setTotalInterestFee(CalculatorUtils.calculateInterestFee(borrowTotalCapital, productDto.getBorrowRatio(), productDto.getPeriodLength()).toString())
                    .setTotalPeriods(totalPeriods)
                    .setPeriodRepaymentCapital(CalculatorUtils.createBillRepaymentCapital(borrowCapital, interestFee).toString())
                    .setPeriodLength(productDto.getPeriodLength())
                    .setBorrowDurationEnum(TradeBorrowDurationEnum.convertByType(productDto.getBorrowDuration()))
                    .setGstCharge(productDto.getGstCharge().toString())
                    .setBorrowRatio(productDto.getBorrowRatio());

            offerResponse.setOfferList(offerVOList);
            LOGGER.info("productDto is {}", JSONObject.toJSONString(offerResponse));
            return offerResponse;
        } catch (Exception e) {

            LOGGER.error("== 转换productDto to  offerResponse 异常==,e,productCode:{}", e, productDto.getProductCode());
            return null;
        }
    }
}
